package com.ruoyi.goods.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//@Configuration
public class MqConfig {
    private static final String Q_ORDER_DELAY = "qqq";
    private static final String EX_ORDER_DELAY_LISTENER = "x";
    private static final String Q_ORDER_DELAY_LISTENER = "aa";

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        cachingConnectionFactory.setUsername("test");
        cachingConnectionFactory.setPassword("123456");
        cachingConnectionFactory.setHost("120.55.41.28");
        cachingConnectionFactory.setPort(5672);
        return cachingConnectionFactory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        return new RabbitTemplate(connectionFactory());
    }

    @Bean(Q_ORDER_DELAY)
    public Queue Q_ORDER_DELAY() {
        Map<String, Object> args = new HashMap<>(2);
        // x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", EX_ORDER_DELAY_LISTENER);
        // x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", Q_ORDER_DELAY_LISTENER);
        // x-message-ttl  声明队列的TTL
        args.put("x-message-ttl", 60000);
        return QueueBuilder.durable(Q_ORDER_DELAY).withArguments(args).build();
    }

    @Bean(Q_ORDER_DELAY_LISTENER)
    public Queue Q_ORDER_DELAY_LISTENER() {
        return new Queue(Q_ORDER_DELAY_LISTENER, true);
    }

    @Bean(EX_ORDER_DELAY_LISTENER)
    public Exchange EX_ORDER_DELAY_LISTENER() {
        return ExchangeBuilder.directExchange(EX_ORDER_DELAY_LISTENER).durable(true).build();
    }

    @Bean
    public Binding BINDING_ORDER_DELAY(@Qualifier(Q_ORDER_DELAY_LISTENER) Queue queue, @Qualifier(EX_ORDER_DELAY_LISTENER) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(Q_ORDER_DELAY_LISTENER).noargs();
    }
}
